<?php

namespace app\api\controller;

use app\common\controller\Api;

use app\common\model\User;
use app\api\common\Program;
use fast\Random;
use think\Config;

/**
 * 首页接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 登录
     */
    public function onLogin()
    {
        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error("code不能为空");
        }
        $config = Config::get("parameter.xcx_config");
        $wx_appid = $config['wx_app_id'];
        $wx_app_secret = $config['wx_app_secret'];
        // var_dump($wx_appid, $wx_app_secret);
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$wx_appid}&secret={$wx_app_secret}&js_code=$code&grant_type=authorization_code";
        $arr = json_decode(curlGet($url), true);
        // $arr['openid'] = 'oApKm66VZlz2NdslZ83IUMMaVqlA';
        if (isset($arr['openid']) && !empty($arr['openid'])) {
            $openid =  $arr['openid'];
            // $info = User::login($openid);
            $info = User::where('openid', $openid)->find();
            if ($info) {
                $this->auth->smallLogin($info->id, 1);
                $data = ['userinfo' => $this->auth->getUserinfo(1)];
                $this->success(__('登录成功'), $data);
            } else {
                $username = Random::alnum(10);
                $password = "123456";
                $email = $username . "@admin.com";
                $mobile = '';
                $openid = $arr['openid'];
                $ret = $this->auth->registeruser($username, $password, $email, $mobile, [], $openid);
                if ($ret) {
                    $this->success('登录成功', ['userinfo' => $this->auth->getUserinfo()]);
                } else {
                    $this->error($this->auth->getError());
                }
            }
        } else {
            $this->error('登录失败,' . $arr['errmsg']);
        }
    }

    /**
     * 授权手机号
     */
    public function bindPhone()
    {
        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error("code不能为空");
        }
        $user_id = $this->auth->id;
        $accessToken = Program::getAccessToken();
        $accessToken = isset($accessToken['data']['access_token']) ? $accessToken['data']['access_token'] : '';
        $get_phone_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$accessToken";
        $requestBody = json_encode(array('code' => $code));
        $context = stream_context_create(['http' => ['method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded" . "Content-Length: " . mb_strlen($requestBody), 'content' => $requestBody]]);
        $response = file_get_contents($get_phone_url, false, $context);
        $arr = json_decode($response, true);
        if ($arr['errcode'] == 0) {
            $phone = $arr['phone_info']['phoneNumber'];
            $user = User::find($user_id);
            $user->mobile = $phone;
            $res = $user->save();
            if ($res !== false) {
                $this->success('绑定成功');
            } else {
                $this->error('绑定失败');
            }
        } else {
            $this->error($arr['errmsg']);
        }
    }
}
